#include "loginpage.h"
#include "director.h"
#include "ui_loginpage.h"

#include <QDebug>
#include <QJsonObject>
#include <QMessageBox>
#include <QUiLoader>

LoginPage::LoginPage(QWidget *parent)
    : AbstractPage(parent), ui(new Ui::LoginPage) {
  ui->setupUi(this);
  ui->lineEdit_2->setText(QString("human%1").arg(rand() % 100));
  ui->lineEdit->setText(QString("room%1").arg(rand() % 100));
}

LoginPage::~LoginPage() { delete ui; }

void LoginPage::on_pushButton_2_clicked() {
  Director::instance()->m_created = false;
  checkInput();
}

void LoginPage::on_pushButton_clicked() {
  Director::instance()->m_created = true;
  checkInput();
}

void LoginPage::on_pushButton_3_clicked() {
  QUiLoader ul;
  QFile file(":/form/helpform.ui");
  QDialog *dlg = static_cast<QDialog *>(ul.load(&file));
  if (dlg != nullptr) {
    Qt::WindowFlags flages = dlg->windowFlags();
    dlg->setWindowFlags(flages & ~(Qt::WindowContextHelpButtonHint));
    dlg->exec();
    delete dlg;
  }
}

void LoginPage::notify(const QJsonObject &obj) {
  if (obj.value("code").toInt() == 0) {
    nextStep();
  } else {
    QString msg = obj.value("msg").toString();
    QMessageBox::information(this, "提示", msg);
  }
}

bool LoginPage::checkInput() {
  QString nick = ui->lineEdit_2->text().trimmed();
  QString room = ui->lineEdit->text().trimmed();

  if (nick.isEmpty() || room.isEmpty()) {
    QMessageBox::information(this, "Tips", "呢称必须填与房间必须填！");
    return false;
  }

  if (!Director::instance()->joinRoom(nick, room)) {
    QMessageBox::information(this, "Tips", "找不到服务器！");
    return false;
  }

  return true;
}

void LoginPage::nextStep() {
  Director::instance()->room = ui->lineEdit->text().trimmed();
  Director::instance()->nick = ui->lineEdit_2->text().trimmed();
  Director::instance()->backward();
}
